# -*- coding: utf-8 -*-

import glob
import os
import configparser
import shutil
import threading

from app.helper.helper import root_path


class Config:
    """
    配置文件操作类

    使用:
    config = Config().init()
    config.get("app","name")
    """

    _instance_lock = threading.Lock()

    def __init__(self):
        self.config_path = os.path.join(root_path(), "config")
        self._config = self._get_config()

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            with cls._instance_lock:
                if not hasattr(cls, '_instance'):
                    cls._instance = object.__new__(cls)

                    # 实例化对象后增加私有属性(必须放在后面)
                    cls._config = cls()._get_config()

        return cls._instance

    def _get_config(self):
        """获取configparser对象实例"""

        self._check_config_file()
        config = self._load_config()

        return config

    def _check_config_file(self):
        """检查配置文件是否存在，不存在则复制"""

        for example_filepath in glob.glob(os.path.join(self.config_path, "*.example")):
            example_filename = os.path.basename(example_filepath)
            example_filedir = os.path.dirname(os.path.abspath(example_filepath))

            ini_filename = example_filename.replace(".example", "")
            ini_filepath = os.path.join(example_filedir, ini_filename)

            if not os.path.exists(ini_filepath):
                shutil.copy(example_filepath, ini_filepath)

    def _load_config(self):
        """循环遍历config文件夹加载所有配置文件"""

        config = configparser.ConfigParser()

        for config_file in glob.glob(os.path.join(self.config_path, "*.ini")):
            config.read(config_file, encoding="utf8")
        return config

    def init(self):
        """初始化返回原生config，可以直接调用使用"""
        return self._config
